package Main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class XMLParser {

	static public String getContents(File aFile) {
		// ...checks on aFile are elided
		StringBuilder contents = new StringBuilder();

		try {
			// use buffering, reading one line at a time
			// FileReader always assumes default encoding is OK!
			BufferedReader input = new BufferedReader(new FileReader(aFile));
			try {
				String line = null; // not declared within while loop
				/*
				 * readLine is a bit quirky : it returns the content of a line
				 * MINUS the newline. it returns null only for the END of the
				 * stream. it returns an empty String if two newlines appear in
				 * a row.
				 */
				while ((line = input.readLine()) != null) {
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			System.out.println("ERROR: xml parse errror " +  aFile.getName());
		}

		return contents.toString();
	}

	public void addMovieFromCinemaURL(MovieDay movieDay, Cinema cinema) {

		String pageString = "";

		// try {
		// URL url = new URL(urlString);
		// URLConnection con = url.openConnection();
		// InputStream in = con.getInputStream();
		// String encoding = con.getContentEncoding();
		// encoding = encoding == null ? "UTF-8" : encoding;
		// pageString = IOUtils.toString(in, encoding);
		// } catch (MalformedURLException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// return;
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		WebsiteReader webReader = new WebsiteReader();
		pageString = webReader.websiteToString(cinema.url);

		// File f = new File("outputFabio.html");

		// pageString = getContents(f);

		// debug
		// System.out.println(pageString);

		SimpleDateFormat dateFormatter = new SimpleDateFormat(
				"EEEE, dd.MM.yyyy");
		StringBuilder todayString = new StringBuilder(
				dateFormatter.format(new Date()));

		String todayStringWithTags = "<h2>" + todayString + "</h2>";

		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.DAY_OF_YEAR, 1); // <--
		Date tomorrow = cal.getTime();

		StringBuilder tomorrowString = new StringBuilder(
				dateFormatter.format(tomorrow));

		String tomorrowStringWithTags = "<h2>" + tomorrowString + "</h2>";

		// todayStringWithTags = todayStringWithTags
		// .replaceAll("Monday", "Montag");
		// todayStringWithTags = todayStringWithTags.replaceAll("Tuesday",
		// "Dienstag");
		// todayStringWithTags = todayStringWithTags.replaceAll("Wednesday",
		// "Mittwoch");
		// todayStringWithTags = todayStringWithTags.replaceAll("Thursday",
		// "Donnerstag");
		// todayStringWithTags = todayStringWithTags.replaceAll("Friday",
		// "Freitag");
		// todayStringWithTags = todayStringWithTags.replaceAll("Saturday",
		// "Samstag");
		// todayStringWithTags = todayStringWithTags.replaceAll("Sunday",
		// "Sonntag");
		//
		// tomorrowStringWithTags = tomorrowStringWithTags.replaceAll("Monday",
		// "Montag");
		// tomorrowStringWithTags = tomorrowStringWithTags.replaceAll("Tuesday",
		// "Dienstag");
		// tomorrowStringWithTags =
		// tomorrowStringWithTags.replaceAll("Wednesday",
		// "Mittwoch");
		// tomorrowStringWithTags =
		// tomorrowStringWithTags.replaceAll("Thursday",
		// "Donnerstag");
		// tomorrowStringWithTags = tomorrowStringWithTags.replaceAll("Friday",
		// "Freitag");
		// tomorrowStringWithTags =
		// tomorrowStringWithTags.replaceAll("Saturday",
		// "Samstag");
		// tomorrowStringWithTags = tomorrowStringWithTags.replaceAll("Sunday",
		// "Sonntag");

		// System.out.println("Today = " + todayStringWithTags);
		// System.out.println("Tomorrow = " + tomorrowStringWithTags);

		int startTodayIndex = pageString.indexOf(todayStringWithTags);
		// System.out.println("TodayIndex = " + startTodayIndex);
		int startTomorrowIndex = pageString.indexOf(tomorrowStringWithTags);
		// System.out.println("TomorrowIndex = " + startTomorrowIndex);

		
		if (startTodayIndex < 0 || startTomorrowIndex < 0 || startTomorrowIndex < startTodayIndex)
		{
			System.out.println("Something is wrong with this page: " + cinema.url +", I will not process it!");
			return;
		}	
		
		
		int currentProcessingFromIndex = startTodayIndex;

		do {

			int startRoomIndexPre = pageString.indexOf("<td width=\"20\"",
					currentProcessingFromIndex) + 14;

			int startRoomIndex = pageString.indexOf(">", startRoomIndexPre) + 1;

			int endRoomIndex = pageString.indexOf("</td>", startRoomIndex);

			String roomString = pageString.substring(startRoomIndex,
					endRoomIndex);

			int startListningstitleIndex = pageString.indexOf(
					"<a class=\"listingtitle\"", endRoomIndex);

			int startTitleIndex = pageString.indexOf("title=\"",
					startListningstitleIndex) + 7;
			int endTitleIndex = pageString.indexOf('"', startTitleIndex);

			String movieTitle = pageString.substring(startTitleIndex,
					endTitleIndex);

			int startLanguageIndex = pageString.indexOf("title=\"Sprachen\">",
					endTitleIndex) + 17;
			int endLanguageIndex = pageString.indexOf("</a>",
					startLanguageIndex);

			String language = pageString.substring(startLanguageIndex,
					endLanguageIndex);

			currentProcessingFromIndex = endTitleIndex;

			if (!language.equals("D")) {
				roomString = roomString.replace(" ", "");
				roomString = roomString.replace("a", "101");
				roomString = roomString.replace("b", "102");
				int roomNr = 0;
				if (!roomString.isEmpty())
					roomNr = Integer.parseInt(roomString);
				movieDay.getMovies().add(
						new Movie(todayString.toString(), cinema, cinema
								.getRoom(roomNr), movieTitle));
			} else {
				System.out.println("--Excluding " + roomString + " - "
						+ movieTitle + ", language=" + language);
			}

		} while (pageString.indexOf("<td width=\"20\"",
				currentProcessingFromIndex) + 14 < startTomorrowIndex);

	}
}
